package com.citywithincity.db;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.Element;

import com.citywithincity.db.drivers.mysql.MysqlConnDescription;
import com.citywithincity.db.drivers.oracle.OracleConnDescription;
import com.citywithincity.utils.IoUtil;
import com.citywithincity.utils.PathUtil;
import com.damai.xml.XMLUtil;
import com.damai.xml.XMLVisitor;

public class DbConfigUtil {


	public static List<ConnectionDescription> loadConfig() throws IOException {
		
		InputStream is = null;
		final List<ConnectionDescription> descriptions = new ArrayList<ConnectionDescription>(3);
		try {
			is = PathUtil.getConfigInputStream(DbConfigUtil.class,"database.xml");
			XMLUtil.loadXmlLevel1(DbConfigUtil.class, "database.xml", new XMLVisitor() {
				
				@Override
				public void onVisit(Element element) {
					// TODO Auto-generated method stub
					String driver = element.getAttribute("driver");
					String user = element.getAttribute("user");
					String password = element.getAttribute("password");
					String host = element.getAttribute("host");
					String port = element.getAttribute("port");
					String database = element.getAttribute("db");
					ConnectionDescription connectionDescription;
					if (driver.equals("oracle")) {
						connectionDescription = new OracleConnDescription(host, Integer.parseInt(port), database, user,
								password);
					} else {
						connectionDescription = new MysqlConnDescription(host, Integer.parseInt(port), database, user,
								password);
					}
					descriptions.add(connectionDescription);
				}
			});
			
			return descriptions;

		} finally {
			IoUtil.close(is);
		}
	}
}
